#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
import os.path
import platform
import re
import string
import subprocess
import sys
import tempfile

# Main.
if __name__ == "__main__":
    #~ Handle options.
    parser = argparse.ArgumentParser(description="Call HandBrakeCLI with some options.")
    parser.add_argument("-q",
                        "--quality",
                        dest="quality",
                        help="use QUALITY for encoding quality (integer, default 24)",
                        default=24,
                        type=int,
                        metavar="QUALITY")
    parser.add_argument("-o",
                      "--output-file", dest="output",
                      help="use FILE for output, no extension required, 'mp4' automatically appended to the name",
                      metavar="FILE")
    parser.add_argument("-s",
                      "--scale", dest="scale",
                      help="use SCALE to specify output video resolution, e.g 640:480 or 640x352; 'none' will bypass scaling",
                      metavar="SCALE")
    parser.add_argument("input", metavar = "INPUT_FILE", help = "Input file.")

    options = parser.parse_args()
    #~ Sanity checking.
    if options.output is None:
        print(">>> Output file was not specified, generating one from the input file's name.", file=sys.stderr)
        options.output = os.path.splitext(options.input)[0]+".mp4"
        print(">>> Output: '{0}'".format(options.output))
    else:
        if not len(os.path.splitext(options.output)[1]):
            options.output+=".mp4"
    if options.quality is None:
        print(">>> Encoding quality was not specified, using the default.", file=sys.stderr)
    if options.scale is None:
        print(">>> Scale not specified.", file=sys.stderr)
        parser.parse_args(["-h"])
    if options.input is None:
        print(">>> No input file specified", file=sys.stderr)
        parser.parse_args(["-h"])

    # Crop and scale only if scale is not 'none'.
    scaleString = "--display-width {0} -w {0} -l {1}"
    if options.scale.lower() != 'none':
        # Video scaling.
        parts = options.scale.replace("x", ":").split(":")
        newWidth = int(parts[0])
        newHeight = int(parts[1])
        # Width/height must be divisible by 16.
        if newWidth % 16:
            newWidth = newWidth + (16 - newWidth % 16)
        if newHeight % 16:
            newHeight = newHeight + (16 - newHeight % 16)
        scaleString = scaleString.format(newWidth, newHeight)
    else:
        scaleString = ""

    # Get an absolute path to target file, since the following chdir()
    # messes up the abspath() -call into some relative directory stuff.
    targetPath = os.path.abspath(options.output)

    #~ CD to video file's directory.
    videoPath, videoFile = os.path.split(os.path.abspath(options.input))
    os.chdir(videoPath)

    #~ Encoder string.
    cmd = string.Template(" ".join(["HandBrakeCLI -a none -i $INPUT -o $OUTPUT",
                "-e x264 -q $QUALITY --x264-tune film -f mp4",
                "-x crf=$QUALITY:bframes=16:b-adapt=2:direct=auto:8x8dct=1:no-dct-decimate=1:cabac=1",
                "--custom-anamorphic $SCALE"]))

    # Ready for run.
    p = subprocess.Popen(cmd.substitute(INPUT=options.input, OUTPUT=options.output, QUALITY=options.quality, SCALE=scaleString).split())
    sts = os.waitpid(p.pid, 0)
